package com.kly.sc.api.application.service.user.impl;

import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import com.alibaba.nacos.api.config.annotation.NacosValue;
import com.fqgj.common.utils.CollectionUtils;
import com.fqgj.common.utils.StringUtils;
import com.kly.dto.ProductBenefitDto;
import com.kly.enums.Benefits;
import com.kly.enums.ProductCategory;
import com.kly.sc.api.application.helper.RequestLocalInfo;
import com.kly.sc.api.application.service.user.BenefitService;
import com.kly.sc.api.application.utils.RpcUtils;
import com.kly.sc.api.application.vo.BenefitDto;
import com.kly.sc.api.application.vo.UserBenefit;
import com.kly.service.ProductService;
import com.kly.user.dto.UserBaseDto;
import com.kly.user.service.AuthLoginService;
import com.kly.user.service.UserService;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;
import java.util.Objects;

@Service
public class BenefitServiceImpl implements BenefitService {

    @Resource
    ProductService productService;
    @Resource
    UserService userService;
    @Resource
    AuthLoginService authLoginService;
    @NacosValue(value = "${white.list}", autoRefreshed = true)
    private String whiteList;


    @Override
    public UserBenefit getSessionConfig(String appCode) {

        BenefitDto newUserBenefit = buildBenefitDto(appCode, ProductCategory.NEW_USER_BENEFITS);
        BenefitDto oldUserBenefit = buildBenefitDto(appCode, ProductCategory.OLD_USER_BENEFITS);

        return UserBenefit.builder().newUserBenefit(newUserBenefit).oldUserBenefit(oldUserBenefit).build();

    }

    @Override
    public ProductCategory getProductCategory(String userCode, String appCode) {

        final UserBaseDto userBaseDto = RpcUtils.getResult(userService.getUserBaseInfo(userCode));
        final Date registerDate = userBaseDto.getGmtCreate();

        // 非当日注册用户走老客控制逻辑
        if (registerDate.before(DateUtil.beginOfDay(new Date()))) {
            return ProductCategory.OLD_USER_BENEFITS;
        }

        // 当日注册用户
        final Boolean isNewUserFlag = RpcUtils.getResult(authLoginService.firstRegister(userCode, appCode));
        if (isNewUserFlag) {
            return ProductCategory.NEW_USER_BENEFITS;
        }

        // 白名单用户
        if (org.apache.commons.lang3.StringUtils.isNotBlank(whiteList)) {
            if (StringUtils.isNotEmpty(userBaseDto.getEmail())) {
                if (whiteList.contains(userBaseDto.getEmail())) {
                    return ProductCategory.NEW_USER_BENEFITS;
                }
            }
            if (StringUtils.isNotEmpty(userBaseDto.getNickName())) {
                if (whiteList.contains(userBaseDto.getNickName())) {
                    return ProductCategory.NEW_USER_BENEFITS;
                }
            }
            if (StringUtils.isNotEmpty(userBaseDto.getMobile())) {
                if (whiteList.contains(userBaseDto.getMobile())) {
                    return ProductCategory.NEW_USER_BENEFITS;
                }
            }
        }
        return ProductCategory.OLD_USER_BENEFITS;
    }

    @Override
    public BenefitDto getChatChatBenefit(String userCode, String appCode) {


        final UserBaseDto userBaseDto = RpcUtils.getResult(userService.getUserBaseInfo(userCode));

        String email = StringUtils.isEmpty(userBaseDto.getEmail()) ? "noData" : userBaseDto.getEmail();
        String nickName = StringUtils.isEmpty(userBaseDto.getNickName()) ? "noData" : userBaseDto.getNickName();
        String mobile = StringUtils.isEmpty(userBaseDto.getMobile()) ? "noData" : userBaseDto.getMobile();

        // 白名单用户
        if (StringUtils.isNotEmpty(whiteList) && (whiteList.contains(email) || whiteList.contains(nickName) || whiteList.contains(mobile))) {
            return buildBenefitDto(appCode, ProductCategory.NEW_USER_BENEFITS);
        } else { // 非白名单用户
            final Boolean isNewUserFlag = RpcUtils.getResult(authLoginService.firstRegister(userCode, RequestLocalInfo.getRequestBasicInfo().getAppCode()));
            // 当日注册用户（之前未在app注册过用户）
            if (isNewUserFlag) {
                return buildBenefitDto(appCode, ProductCategory.NEW_USER_BENEFITS);
            } else {
                final String registerDate = DateUtil.format(userBaseDto.getGmtCreate(), DatePattern.NORM_DATE_FORMAT);
                final String currentDate = DateUtil.format(new Date(), DatePattern.NORM_DATE_FORMAT);
                // 非当日注册用户走老客控制逻辑
                final BenefitDto benefitDto = buildBenefitDto(appCode, ProductCategory.OLD_USER_BENEFITS);
                if (Objects.equals(registerDate, currentDate)) {
                    return benefitDto;
                } else {
                    benefitDto.setEffectiveChatLimitNum(0);
                    benefitDto.setDeepChatLimitNum(0);
                    benefitDto.setOverLimitChat(0);
                    return benefitDto;
                }
            }
        }
    }

    private BenefitDto buildBenefitDto(String appCode, ProductCategory productCategory) {
        final List<ProductBenefitDto> benefitDtos = RpcUtils.getResult(productService.listProductBenefit(appCode, productCategory.getCode()));
        if (CollectionUtils.isNotEmpty(benefitDtos)) {
            final BenefitDto.BenefitDtoBuilder benefitBuilder = BenefitDto.builder().productCategory(productCategory);
            for (ProductBenefitDto dto : benefitDtos) {
                if (Benefits.ICE_BREAKING_SESSION.getBenefitCode() == dto.getBenefitCode()) {
                    benefitBuilder.firstChatLimitNum(dto.getLimitQuantity());
                }
                if (Benefits.EFFECTIVE_SESSION.getBenefitCode() == dto.getBenefitCode()) {
                    benefitBuilder.effectiveChatLimitNum(dto.getLimitQuantity());
                }
                if (Benefits.DEEP_SESSION.getBenefitCode() == dto.getBenefitCode()) {
                    benefitBuilder.deepChatLimitNum(dto.getLimitQuantity());
                }
                if (Benefits.SESSION_MESSAGE_LIMIT.getBenefitCode() == dto.getBenefitCode()) {
                    benefitBuilder.overLimitChat(dto.getLimitQuantity());
                }
            }
            return benefitBuilder.build();
        }
        return BenefitDto.builder().build();
    }
}
